#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time   : 2025-03-10 9:21:04
# @Author : 搬砖客

import datetime
import os
from common.yaml_util import YamlUtil


def write_case(case_path, page):
    with open(case_path, 'w', encoding="utf-8") as f:
        f.write(page)


# todo 新增跳过和跳过原因的关键字
def write_testcase_file(class_title, func_title, case_path, testdata_path, file_name, whether_skip=None, skip_reason=None):
    """

        :param file_name:
        :param class_title: 类名称
        :param func_title: 函数名称
        :param case_path: case 路径
        :param testdata_path: 测试用例数据的文件路径
        :param whether_skip: 是否跳过该用例
        :param skip_reason: 跳过该用例的理由
        :return:
        """
    author = YamlUtil.read_testdata_yaml("author")
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    real_time_update_test_cases = YamlUtil.read_testdata_yaml("real_time_update_test_cases")

    page = f'''#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time   : {now}
# @Author : {author}

import tracemalloc
import time
import unittest

from ddt import data, ddt, unpack, file_data
from keywords.library import Library
from common.read_excel import ReadExcel
from common.get_logger import GetLogger
from config import config
import warnings

log = GetLogger.get_logger()


@ddt
class Test{class_title}(unittest.TestCase):
    # 实现一条用例覆盖所有用例的测试
    # 每条用例的数据，测试数据+关键字函数
    excel = ReadExcel(filename="{testdata_path}")
    datas = excel.get_cases_data()

    @classmethod
    def setUpClass(cls) -> None:
        warnings.simplefilter("ignore", ResourceWarning)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.excel.write_case_result()

    @data(*datas)
    def test_{func_title}(self, casedata):
        time.sleep(1)
        log.info("-*"*30)
        log.info("-*"*30)
        step_datas = casedata['step_datas']
        case_name = casedata['case_name']
        log.info(f"【%s】的测试步骤的数据为:%s" % (case_name,step_datas))

        # 用例体 = 操作步骤+断言
        # 封装对应的方法，执行所有用例的操作步骤
        lib = Library()
        # index为0的时候，行数为2.所以row=index + 2
        for index, step_data in enumerate(step_datas):
            # 执行每条用例的操作步骤
            log.info(f"文件中的测试步骤为：%s" % (step_data))
            try:
                # 写入操作时间
                self.excel.write_step_time(sheet_name=case_name, row=index + 2)
                lib.run(*step_data)

                # 写入测试结果为pass
                self.excel.write_step_result(sheet_name=case_name, row=index + 2, col=config.case_result,
                                             result="pass")
            except Exception as e:
                # 当前测试用例执行结果为fail
                self.excel.write_step_result(sheet_name=case_name, row=index + 2, col=config.case_result,
                                             result="fail")
                raise AssertionError("测试用例执行失败")
'''
    if real_time_update_test_cases:
        write_case(case_path=case_path, page=page)
    elif real_time_update_test_cases is False:
        if not os.path.exists(case_path):
            write_case(case_path=case_path, page=page)
    else:
        raise ValueError("real_time_update_test_cases 配置不正确，只能配置 True 或者 False")
